import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_01/api/user.dart';

import '../../utils/Toast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Timer? _timer;
  int _count = 60;

  // 手机号
  final TextEditingController _phoneController = TextEditingController();
  // 验证码
  final TextEditingController _codeController = TextEditingController();
  // 测试代码登录 提示获取手机号信息
  login(){
    PromptAction.showToast( _phoneController.text );
  }

 // 获取验证码
   _sentCode() async  {
    if(_count == 60){
      // 一进入函数就立刻执行 把 _count 变为 59
      // setState(() {
      //   _count --;
      // });
      // 非空校验
      if(_phoneController.text.isEmpty){
        return PromptAction.showToast('手机号不能为空');
      }
      // 手机号正则校验
      RegExp reg = RegExp(r'^1[3-9]\d{9}$');
      if(!reg.hasMatch(_phoneController.text)){
        return PromptAction.showToast('手机号格式不正确');
      }
       setState(() {
        _count --;
      });
      // 发送请求获取验证码
      final res = await getCodeAPI({ 'mobile': _phoneController.text });
      // 延时器
      Future.delayed(const Duration(seconds: 2), (){
        _codeController.text = res['code'];
      });
      // 开启倒计时
      beginCount();
    }
   }
 // 开启倒计时
  beginCount(){
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if(_count == 0){
          // 重置秒数
          _count = 60;
          // 取消定时器
          _timer?.cancel();
        } else {
         _count--;
        }
        // 秒数减到0秒之后 重新更新状态
        setState(() {});
      });
  }
  

  Widget getTimeShow(){
    if(_count < 60){
      return  Text('还剩$_count s');
    } else {
      return const Text('获取验证码');
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // 销毁定时器
    _timer?.cancel();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                 Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    // TODO: 发送验证码
                   _sentCode();
                  },
                  child: getTimeShow(),
                ),
              ],

            ),
            const SizedBox(height: 8),
             TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
